package com.yoooya.base.third.utils.http;

import com.yoooya.base.third.common.error.WxError;
import com.yoooya.base.third.common.error.WxErrorException;
import com.yoooya.base.third.model.vo.WxMediaUploadResult;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.File;
import java.io.IOException;

/**
 * 上传媒体文件请求执行器，请求的参数是File, 返回的结果是String
 * 
 * 
 * @创建人 Sun Yijing
 * @创建时间 2018-07-08
 */
public class MediaUploadRequestExecutor implements
		RequestExecutor<WxMediaUploadResult, File> {

	@Override
	public WxMediaUploadResult execute(CloseableHttpClient httpclient,
			String uri, File file) throws WxErrorException,
            ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(uri);
		if (file != null) {
			HttpEntity entity = MultipartEntityBuilder.create()
					.addBinaryBody("media", file)
					.setMode(HttpMultipartMode.RFC6532).build();
			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type",
					ContentType.MULTIPART_FORM_DATA.toString());
		}
		try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
			String responseContent = Utf8ResponseHandler.INSTANCE
					.handleResponse(response);
			WxError error = WxError.fromJson(responseContent);
			if (error.getErrorCode() != 0) {
				throw new WxErrorException(error);
			}
			return WxMediaUploadResult.fromJson(responseContent);
		}
	}

}
